#!/bin/bash

set -e

mkdir -p /dev/bus/usb
mount -t devtmpfs none /dev/bus/usb || true

mkdir -p /var/log/cups
touch /var/log/cups/error_log


service dbus start
service avahi-daemon start

/usr/sbin/cupsd -f -c /etc/cups/cupsd.conf &


sleep 5


if ! lpstat -v | grep -q "HL-2260D"; then
    echo "Searching for Brother HL-2260D printer..."
    sleep 10
    if lsusb | grep -i "Brother"; then
        echo "Brother printer detected via USB"
        lpadmin -p HL-2260D -E -v usb://Brother/HL-2260D \
            -P /opt/brother/Printers/HL2260D/cupswrapper/brother_hl2260d_printer_en.ppd
        cupsenable HL-2260D
        cupsaccept HL-2260D
        lpoptions -d HL-2260D
        echo "Printer HL-2260D has been configured"
    else
        echo "No Brother printer detected. Please connect the printer and restart the container."
    fi
fi

echo "CUPS server is running. Access the web interface at http://localhost:631"
tail -f /var/log/cups/error_log